//
//  AGLiveRoomViewController.m
//  ZFJOpenLive
//
//  Created by ZhangFujie on 2021/12/10.
//

#import "AGLiveRoomViewController.h"
#import "AGUserView.h"
#import "AGBaseView.h"
#import "AGMoreView.h"
#import "AGBottomBtnsView.h"
#import <libCNamaSDK/FURenderer.h>
#import "AGConnectionStateView.h"

@interface MIMediaPlayer : NSObject<AgoraRtcMediaPlayerProtocol>

@end

@interface AGLiveRoomViewController ()<AgoraRtcEngineDelegate, AgoraMediaMetadataDelegate>

///
@property (nonatomic,strong) UIView *broadcastersView;
///
@property (nonatomic,strong) AgoraRtcEngineKit *agoraKit;
/// 美颜的数据
@property (nonatomic,strong) AgoraBeautyOptions *beautyOptions;
/// 翻转摄像头 美颜 关闭摄像头 关闭麦克风
@property (nonatomic,strong) AGBottomBtnsView *bottomBtnsView;
///
@property (nonatomic,strong) UIImageView *exitImgView;
///
@property (nonatomic,strong) UIImageView *moreView;
///
@property (nonatomic,strong) AGUserView *userView;
///
@property (nonatomic,strong) AGConnectionStateView *connectionStateView;

@end

@implementation AGLiveRoomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 调用初始化视频窗口函数
    [self initViews];
    // 后续步骤调用 Agora API 使用的函数
    [self initializeAgoraEngine];
    [self setChannelProfile];
    [self setClientRole];
    [self setupLocalVideo];
    [self joinChannel];
}

- (void)initViews {
    [self.broadcastersView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo(self.view);
    }];
    
    if([AGPersoninfor sharedInstance].agoraClientRole == AgoraClientRoleBroadcaster){
        [self.bottomBtnsView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(- ag_safeBottomOffset());
            make.height.mas_equalTo(49);
        }];
        
        [self.connectionStateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.bottomBtnsView.mas_top);
            make.height.mas_equalTo(49);
        }];
    }
    
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(self.view).offset(ag_statusBarHeight() + 20);
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(44);
    }];
    
    [self.exitImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(- 15);
        make.centerY.equalTo(self.userView);
        make.width.height.mas_equalTo(30);
    }];
    
    [self.moreView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.exitImgView.mas_left).offset(- 10);
        make.centerY.equalTo(self.userView);
        make.width.height.mas_equalTo(30);
    }];
}

/// 初始化 AgoraRtcEngineKit 对象
- (void)initializeAgoraEngine{
    self.agoraKit = [AgoraRtcEngineKit sharedEngineWithAppId:[AGPersoninfor sharedInstance].appId delegate:self];
    
    /// 网络质量探测 --- 》》》 这个必须是在加入频道之前调用
//    AgoraLastmileProbeConfig *config = [[AgoraLastmileProbeConfig alloc] init];
//    // 确认进行上行网络探测
//    config.probeUplink = YES;
//    // 确认进行下行网络探测
//    config.probeDownlink = YES;
//    // 期望的最大上行码率，单位为 bps，取值范围 [100000,5000000]
//    config.expectedUplinkBitrate = 100000;
//    // 期望的最大下行码率，单位为 bps，取值范围 [100000,5000000]
//    config.expectedDownlinkBitrate = 100000;
//    // 调用 startLastmileProbeTest 开启网络探测
//    [self.agoraKit startLastmileProbeTest:config];
}

/// 设置频道场景
- (void)setChannelProfile {
    [self.agoraKit setChannelProfile:AgoraChannelProfileLiveBroadcasting];
    // 开黑聊天室
    [self.agoraKit setAudioProfile: AgoraAudioProfileSpeechStandard scenario: AgoraAudioScenarioChatRoom];
//    // 娱乐聊天室
//    [self.agoraKit setAudioProfile: AgoraAudioProfilemusicStandard, scenario: AgoraAudioScenarioChatRoomEntertainment];
//    // K 歌房
//    [self.agoraKit setAudioProfile: AgoraAudioProfileMusicHighQuality, scenario: AgoraAudioScenarioChatRoomEntertainment];
//    // FM 超高音质
//    [self.agoraKit setAudioProfile: AgoraAudioProfilemusicHighQuality, scenario: AgoraAudioScenarioGameStreaming]
    
    /// 设置鉴黄
//    AgoraContentInspectModule *module1 = [[AgoraContentInspectModule alloc] init];
//    module1.type = AgoraContentInspectTypeModeration;
//    module1.interval = 2;
//
//    AgoraContentInspectConfig *config = [[AgoraContentInspectConfig alloc] init];
//    config.modules = @[module1];
//    [self.agoraKit enableContentInspect:YES config:config];
}

/// 设置用户角色
- (void)setClientRole {
    [self.agoraKit setClientRole:[AGPersoninfor sharedInstance].agoraClientRole];
}

- (void)setupLocalVideo {
    /// 启用视频模块
    [self.agoraKit enableVideo];
    ///
    if([AGPersoninfor sharedInstance].agoraClientRole == AgoraClientRoleBroadcaster){
        AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
        videoCanvas.uid = 0;
        videoCanvas.renderMode = AgoraVideoRenderModeHidden;
        videoCanvas.view = self.broadcastersView;
        /// 设置本地视图
        [self.agoraKit setupLocalVideo:videoCanvas];
        /// 开启本地预览
        [self.agoraKit startPreview];
    }
}

/// 频道内每个用户的 uid 必须是唯一的
- (void)joinChannel {
//    /// 开启耳返功能
//    [self.agoraKit enableInEarMonitoring:YES];
//    /// 设置耳返音量
//    [self.agoraKit setInEarMonitoringVolume:100];
    
    AgoraRtcChannelMediaOptions *option = [[AgoraRtcChannelMediaOptions alloc] init];
    option.channelProfile = [AgoraRtcIntOptional of:AgoraChannelProfileLiveBroadcasting];
    option.clientRoleType = [AgoraRtcIntOptional of:(int)[AGPersoninfor sharedInstance].agoraClientRole];
    
    [self.agoraKit joinChannelByToken:[AGPersoninfor sharedInstance].token channelId:[AGPersoninfor sharedInstance].channelId uid:[AGPersoninfor sharedInstance].uid mediaOptions:option joinSuccess:^(NSString * _Nonnull channel, NSUInteger uid, NSInteger elapsed) {
        NSLog(@"channel == %@, uid == %ld, elapsed == %ld",channel, uid, elapsed);
    }];
}

/// 同时加入两个频道，一个频道发送麦克风音频流，一个频道发送camera视频流
- (void)joinTwoChannelWithUid:(NSInteger)uid micChannel:(NSString *)micChannel cameraChannel:(NSString *)cameraChannel{
    /// 发送麦克风音频流
    AgoraRtcChannelMediaOptions *mediaOptions = [[AgoraRtcChannelMediaOptions alloc] init];
    mediaOptions.autoSubscribeAudio = [AgoraRtcBoolOptional of:NO];
    mediaOptions.autoSubscribeVideo = [AgoraRtcBoolOptional of:NO];
    /// 不发布摄像头采集的视频
    mediaOptions.publishCameraTrack = [AgoraRtcBoolOptional of:NO];
    /// 发布采集到的音频
    mediaOptions.publishAudioTrack = [AgoraRtcBoolOptional of:YES];
    mediaOptions.clientRoleType = [AgoraRtcIntOptional of:1];
    /// 加入频道1
    [self.agoraKit joinChannelByToken:nil channelId:micChannel uid:uid mediaOptions:mediaOptions joinSuccess:nil];
    
    /// 发送camera视频流
    AgoraRtcChannelMediaOptions *mediaOptions2 = [[AgoraRtcChannelMediaOptions alloc] init];
    mediaOptions2.autoSubscribeAudio = [AgoraRtcBoolOptional of:NO];
    mediaOptions2.autoSubscribeVideo = [AgoraRtcBoolOptional of:NO];
    /// 发布摄像头采集的视频
    mediaOptions2.publishCameraTrack = [AgoraRtcBoolOptional of:YES];
    /// 不发布采集到的音频
    mediaOptions2.publishAudioTrack = [AgoraRtcBoolOptional of:NO];
    mediaOptions2.clientRoleType = [AgoraRtcIntOptional of:1];
    
    AgoraRtcConnection *connection = [[AgoraRtcConnection alloc] init];
    connection.channelId = cameraChannel;
    connection.localUid = uid;
    /// 加入频道2
    [self.agoraKit joinChannelExByToken:nil connection:connection delegate:self mediaOptions:mediaOptions2 joinSuccess:nil];
}

/// 成功加入频道回调。
/// uid 加入频道的用户 ID。
/// elapsed 从本地调用 joinChannelByToken [2/2] 开始到发生此事件过去的时间（毫秒）。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didJoinChannel:(NSString * _Nonnull)channel withUid:(NSUInteger)uid elapsed:(NSInteger)elapsed{
    [MBProgressHUD showMessage:[NSString stringWithFormat:@"加入频道用时%ld秒",elapsed]];
}

/// 成功重新加入频道回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didRejoinChannel:(NSString * _Nonnull)channel withUid:(NSUInteger)uid elapsed:(NSInteger) elapsed{
    [MBProgressHUD showSuccess:@"成功重新加入频道"];
}

/// 直播场景下用户角色已切换回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didClientRoleChanged:(AgoraClientRole)oldRole newRole:(AgoraClientRole)newRole{
    [MBProgressHUD showSuccess:@"直播场景下用户角色已切换"];
}

/// 离开频道回调。
/// App 调用 leaveChannel [1/2] 方法时，SDK 提示 app 离开频道成功
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didLeaveChannelWithStats:(AgoraChannelStats * _Nonnull)stats{
    [MBProgressHUD showSuccess:@"离开频道回调"];
}

/// 远端用户（通信场景）/主播（直播场景）加入当前频道回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed{
    AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
    videoCanvas.uid = uid;
    videoCanvas.renderMode = AgoraVideoRenderModeHidden;
    videoCanvas.view = self.broadcastersView;
    /// 设置远端视图
    [self.agoraKit setupRemoteVideo:videoCanvas];
}

/// 远端用户（通信场景）/主播（直播场景）离开当前频道回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason{
    [MBProgressHUD showSuccess:@"离开频道回调"];
}

/// 远端用户（通信场景）/主播（直播场景）停止或恢复发送音频流回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didAudioMuted:(BOOL)muted byUid:(NSUInteger)uid{
    [MBProgressHUD showSuccess:@"主播（直播场景）停止或恢复发送音频流回调。"];
}

/// 本地网络类型发生改变回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine networkTypeChanged:(AgoraNetworkType)type{
    self.connectionStateView.networkType = type;
}

/// 上行网络信息变化回调。
- (void)rtcEngine:(AgoraRtcEngineKit *_Nonnull)engine uplinkNetworkInfoUpdate:(AgoraUplinkNetworkInfo *_Nonnull)networkInfo{
    /// 目标视频编码器的码率 (bps)。
    NSLog(@"networkInfo.videoEncoderTargetBitrateBps == %d", networkInfo.videoEncoderTargetBitrateBps);
}

/// 网络连接中断，且 SDK 无法在 10 秒内连接服务器回调。
- (void)rtcEngineConnectionDidLost:(AgoraRtcEngineKit * _Nonnull)engine{
    NSLog(@"网络连接中断，且 SDK 无法在 10 秒内连接服务器回调。");
}

- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine connectionStateChanged:(AgoraConnectionState)state reason:(AgoraConnectionChangedReason)reason{
    self.connectionStateView.connectionStateType = state;
}

/// Token 已过期回调。
- (void)rtcEngineRequestToken:(AgoraRtcEngineKit * _Nonnull)engine{
    NSLog(@"Token 已过期回调。");
}

/// Token 服务将在30s内过期回调。
- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine tokenPrivilegeWillExpire:(NSString *_Nonnull)token{
    NSLog(@"Token 服务将在30s内过期回调。");
}

- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine didOccurError:(AgoraErrorCode)errorCode{
    NSLog(@"errorCode == %ld", errorCode);
}

/// 退出频道
- (void)exitImgViewClick{
    [self.agoraKit setupLocalVideo:nil];
    [self.agoraKit leaveChannel:nil];
    if([AGPersoninfor sharedInstance].agoraClientRole == AgoraClientRoleBroadcaster){
        [self.agoraKit stopPreview];
    }
    /// 离开频道后，如果你想释放 Agora SDK 使用的所有资源，需调用 destroy 销毁 AgoraRtcEngineKit 对象。
    [AgoraRtcEngineKit destroy];
    [self.navigationController popViewControllerAnimated:YES];
}

/// 更多
- (void)moreViewClick{
    [AGMoreView showMoreViewWithRtcEngine:self.agoraKit completion:^(NSInteger type) {

    }];
}

- (UIView *)broadcastersView{
    if(_broadcastersView == nil){
        _broadcastersView = [[UIView alloc] init];
        [self.view addSubview:_broadcastersView];
    }
    return _broadcastersView;
}

- (AGBottomBtnsView *)bottomBtnsView{
    if(_bottomBtnsView == nil){
        WEAKBLOCK;
        _bottomBtnsView = [[AGBottomBtnsView alloc] init];
        _bottomBtnsView.backgroundColor = ag_randomColorAlpha(0.3);
        _bottomBtnsView.bottomBtnBlock = ^(UIButton *button, AGBottomBtnType type) {
            if(type == AGSwitchCameraBtnType){
                /// 转换摄像头的按钮
                [weakSelf.agoraKit switchCamera];
            }else if(type == AGBeautyBtnType){
                /// 打开关闭美颜
                [weakSelf.agoraKit setBeautyEffectOptions:!button.selected options:weakSelf.beautyOptions];
            }else if(type == AGMuteVideoBtnType){
                /// 关闭视频推流
                [weakSelf.agoraKit muteLocalVideoStream:!button.selected];
            }else if(type == AGMuteAudioBtnType){
                /// 关闭声音推流
                [weakSelf.agoraKit muteLocalAudioStream:!button.selected];
            }
        };
        [self.view addSubview:_bottomBtnsView];
    }
    return _bottomBtnsView;
}

- (AGUserView *)userView{
    if(_userView == nil){
        _userView = [[AGUserView alloc] init];
        _userView.backgroundColor = [UIColor ag_colorWithHexStr:@"#000000" alpha:0.3];
        _userView.layer.masksToBounds = YES;
        _userView.layer.cornerRadius = 22;
        [self.view addSubview:_userView];
    }
    return _userView;
}

- (UIImageView *)exitImgView{
    if(_exitImgView == nil){
        WEAKBLOCK;
        _exitImgView = [[UIImageView alloc] init];
        _exitImgView.image = [UIImage imageNamed:@"icon-exit"];
        _exitImgView.backgroundColor = [UIColor ag_colorWithHexStr:@"#000000" alpha:0.3];
        _exitImgView.layer.masksToBounds = YES;
        _exitImgView.layer.cornerRadius = 15;
        _exitImgView.touchUpInsideBlock = ^(UIView *sender) {
            [weakSelf exitImgViewClick];
        };
        [self.view addSubview:_exitImgView];
    }
    return _exitImgView;
}

- (UIImageView *)moreView{
    if(_moreView == nil){
        WEAKBLOCK;
        _moreView = [[UIImageView alloc] init];
        _moreView.image = [UIImage imageNamed:@"icon-more"];
        _moreView.backgroundColor = [UIColor ag_colorWithHexStr:@"#000000" alpha:0.3];
        _moreView.layer.masksToBounds = YES;
        _moreView.layer.cornerRadius = 15;
        _moreView.touchUpInsideBlock = ^(UIView *sender) {
            [weakSelf moreViewClick];
        };
        [self.view addSubview:_moreView];
    }
    return _moreView;
}

- (AgoraBeautyOptions *)beautyOptions{
    if(_beautyOptions == nil){
        _beautyOptions = [[AgoraBeautyOptions alloc] init];
        /// 对比度，常与 lighteningLevel 搭配使用。取值越大，明暗对比程度越大。
        _beautyOptions.lighteningContrastLevel = AgoraLighteningContrastHigh;
        /// 美白程度，取值范围为 [0.0,1.0]，其中 0.0 表示原始亮度。默认值为 0.6。取值越大，美白程度越大。
        _beautyOptions.lighteningLevel = 0.9;
        /// 磨皮程度，取值范围为 [0.0,1.0]，其中 0.0 表示原始磨皮程度。默认值为 0.5。取值越大，磨皮程度越大。
        _beautyOptions.smoothnessLevel = 0.9;
        /// 红润度，取值范围为 [0.0,1.0]，其中 0.0 表示原始红润度。默认值为 0.1。取值越大，红润程度越大。
        _beautyOptions.rednessLevel = 0.9;
        /// 锐度，取值范围为 [0.0,1.0]，其中 0.0 表示原始锐度，默认值为 0.1。
        _beautyOptions.sharpnessLevel = 0.9;
    }
    return _beautyOptions;
}

- (AGConnectionStateView *)connectionStateView{
    if(_connectionStateView == nil){
        _connectionStateView = [[AGConnectionStateView alloc] init];
        _connectionStateView.backgroundColor = ag_randomColorAlpha(0.3);
        [self.view addSubview:_connectionStateView];
    }
    return _connectionStateView;
}

//- (AgoraMediaPlayer *)mediaPlayer{
//    if(_mediaPlayer == nil){
//        _mediaPlayer = [[AgoraMediaPlayer alloc] initWithDelegate:self];
//    }
//    return _mediaPlayer;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
